<?php
declare (strict_types = 1);

namespace app\controller;

use think\Request;
use app\BaseController;
use think\facade\View;
use think\facade\Session;
use app\model\VisitorShowroom as ShowroomModel;
use app\model\SettingCar as CarModel;
use app\model\SettingUser as UserModel;
use app\model\SalesOrder as OrderModel;
use app\middleware\CheckLogin;

class Showroom extends BaseController
{

    // 注册控制器中间件
    protected $middleware = [CheckLogin::class];


    /**
     * 显示客流信息列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        
        $endDate = $request->param('endDate');

        if(empty($startDate)){
            $startDate = date("Y-m-d H:i:s",strtotime("-30 day"));
        }else{
            $startDate = $request->param('startDate');
        }

        if(empty($endDate)){
            $endDate = date("Y-m-d H:i:s",time());
        }else{
            $endDate = $request->param('endDate');
        }

        $visitorData = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->order('create_date', 'desc')->order('id', 'desc')->select();
        View::assign('visitorData',$visitorData);

        return view('index');
        // dump($startDate,$endDate);
    }

    /**
     * 客流数据json列表
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function indexJson(Request $request)
    {

        //获取传来的条件数据
        $request = $request->param();

        //返回让表格绘制表格的指令
        $data['draw'] = intval($request['draw']);

        //总记录数
        $data['recordsTotal'] = ShowroomModel::count();

            //记录起
        $start = $request['start'];

        //查询长度
        $length = $request['length'];

        //排序条件
        $order = $request['order']['0']['column'];

        // //排序条件
        $orderArr = [ 0 =>'create_date', 1 =>'sales', 2 =>'name',7 =>'features'];

        //获取要排序的字段
        $orderField = (empty($orderArr[$order]))?'deliver_date':$orderArr[$order];

        //排序方式
        $asc = $request['order']['0']['dir'];

        //获取搜索后记录数
        if(!empty($request['search']['value'])){
            $research = ShowroomModel::where('create_date|sales|name|features','like','%'.$request['search']['value'].'%')->select();
            $data['recordsFiltered'] = count($research);
        }else{
            $data['recordsFiltered'] = $data['recordsTotal'];
        }

        //获取客户接待数据
        $customerData = ShowroomModel::field('id,create_date,sales,name,sex,phone,type,sources,vehicle,features')->where('create_date|sales|name|features','like','%'.$request['search']['value'].'%')->order($orderField,$asc)->limit(intval($start), intval($length))->select();

        for ($i=0; $i < count($customerData); $i++) { 
            $customerData[$i]['create_date'] = date('m月d日',strtotime($customerData[$i]['create_date']));
            $customerData[$i]['username'] = Session::get('username');
            if($customerData[$i]['sex'] == 1){
                $customerData[$i]['name'] = mb_substr($customerData[$i]['name'],0,6)." 先生";
            }else{
                $customerData[$i]['name'] = mb_substr($customerData[$i]['name'],0,6)." 女士";
            }
        }

        $data['data'] = $customerData;

        return json($data);
        // dump($data);

    }

    /**
     * 数据分析页面
     *
     * @return \think\Response
     */
    public function analysis()
    {
        //渲染首页
        return view('analysis');
    }

    /**
     * 返回日期编号及对比数据的json
     *
     * @return \think\Response
     */
    public function analysisJson(Request $request)
    {
        //根据模式调用API输入始末时间及日期标识
        $daterange = $request->param('daterange');

        //获取始末日期
        $date = DateInterval($daterange);

        //数据总计

        /////////////////////////////////////
        //客流同比
        //本周期客流
        $VistorCount['thisCount'] = ShowroomModel::whereTime('create_date','between',[$date['thisStart'],$date['thisEnd']])->count();
        //上周期客流
        $VistorCount['lastCount'] = ShowroomModel::whereTime('create_date','between',[$date['lastStart'],$date['lastEnd']])->count();
        //计算客流同比
        if($VistorCount['lastCount'] > 0){
            $visitorChainRatio = ($VistorCount['thisCount'] - $VistorCount['lastCount'])/$VistorCount['lastCount'] * 100;
            if($visitorChainRatio > 0){
                $VistorCount['visitorChainRatio'] = "+".$visitorChainRatio."%";
            }else{
                $VistorCount['visitorChainRatio'] = $visitorChainRatio."%";
            }
        }else{
            $VistorCount['visitorChainRatio'] = "无";
        }
        //本周期新增客流
        $VistorCount['thisNewVisitorCount'] = ShowroomModel::where('type','首次')->whereTime('create_date','between',[$date['thisStart'],$date['thisEnd']])->count();
        
        $data['VistorCount'] = $VistorCount;

        //线图部分
        /////////////////////////////////////////////////////////////////

        //销售顾问接待数据图

        //本期数据
        $sales = ShowroomModel::whereTime('create_date','between',[$date['lastStart'],$date['thisEnd']])->Distinct(true)->column('sales');

        if(!empty($sales)){
            for($i=0; $i < count($sales); $i++) { 
                $salesData[$i]['name'] = $sales[$i];
                $salesData[$i]['this'] = ShowroomModel::whereTime('create_date','between',[$date['thisStart'],$date['thisEnd']])->where('sales',$sales[$i])->count();
                $salesData[$i]['last'] = ShowroomModel::whereTime('create_date','between',[$date['lastStart'],$date['lastEnd']])->where('sales',$sales[$i])->count();
            }
            $data['salesData'] = $salesData;
        }
    
        //客流数据部分
        $thisStart = $date['thisStart'];
        $lastStart = $date['lastStart'];

        for($x=0;$x<$date['maxDays'];$x++){

            //日期赋值
            $lineData[$x]['datetag'] = date('d',$thisStart)."日";

            //总客流数据图

            //本期数据
            $thisVisitorData = ShowroomModel::where('create_date',date('Y-m-d H:i:s',$thisStart))->count();
            $lineData[$x]['thisVisitorData'] = $thisVisitorData;

            //上期数据
            $lastVisitorData = ShowroomModel::where('create_date',date('Y-m-d H:i:s',$lastStart))->count();
            $lineData[$x]['lastVisitorData'] = $lastVisitorData;

            //首次客流数据图

            //本期数据
            $thisFirstVisitorData = ShowroomModel::where(['create_date' => date('Y-m-d H:i:s',$thisStart),'type' => '首次'])->count();
            $lineData[$x]['thisFirstVisitorData'] = $thisFirstVisitorData;

            //上期数据
            $lastFirstVisitorData = ShowroomModel::where(['create_date' => date('Y-m-d H:i:s',$lastStart),'type' => '首次'])->count();
            $lineData[$x]['lastFirstVisitorData'] = $lastFirstVisitorData;

            //再次客流数据图

            //本期数据
            $thisLastVisitorData = ShowroomModel::where(['create_date' => date('Y-m-d H:i:s',$thisStart),'type' => '再次'])->count();
            $lineData[$x]['thisLastVisitorData'] = $thisLastVisitorData;

            //上期数据
            $lastLastVisitorData = ShowroomModel::where(['create_date' => date('Y-m-d H:i:s',$lastStart),'type' => '再次'])->count();
            $lineData[$x]['lastLastVisitorData'] = $lastLastVisitorData;


            //本周期日期增加
            $thisStart = strtotime("+1day",$thisStart);//加一天
            $thisData = array();

            //上周期日期增加
            $lastStart = strtotime("+1day",$lastStart);//加一天
            $lastData = array();
            
        }

        $data['lineData'] = $lineData;

        //饼图部分
        /////////////////////////////////////////////////////////////////////////

        //统计区间数据
        $statisticsData = $this->statistics($date['thisStart'],$date['thisEnd']);

        //渠道数据
        if(!empty($statisticsData['sources'])){
            $sources = $statisticsData['sources'];
            $sourcesRatio['label'] = array();
            $sourcesRatio['data'] = array(); 
            foreach ($sources as $key => $value) {
                array_push($sourcesRatio['label'],$key);
                array_push($sourcesRatio['data'],$value);
            }
        }else{
            $sourcesRatio['label'] = array("无数据");
            $sourcesRatio['data'] = array(0);
        }
        $data['sourcesRatio'] = $sourcesRatio;

        //性别数据
        if(!empty($statisticsData['sex'])){
            $sex = $statisticsData['sex'];
            $sexRatio['label'] = array();
            $sexRatio['data'] = array(); 
            foreach ($sex as $key => $value) {
                //将男1女0的数据翻译成标签
                if($key == 1){
                    array_push($sexRatio['label'],'男');
                }else{
                    array_push($sexRatio['label'],'女');
                }
                array_push($sexRatio['data'],$value);
            }
            
        }else{
            $sexRatio['label'] = array("无数据");
            $sexRatio['data'] = array(0);
        }
        $data['sexRatio'] = $sexRatio;
        

        //信息来源渠道数据
        if(!empty($statisticsData['origin'])){
            $origin = $statisticsData['origin'];
            $originRatio['label'] = array();
            $originRatio['data'] = array(); 
            foreach ($origin as $key => $value) {
                array_push($originRatio['label'],$key);
                array_push($originRatio['data'],$value);
            }
        }else{
            $originRatio['label'] = array("无数据");
            $originRatio['data'] = array(0);
        }
        $data['originRatio'] = $originRatio;
        

        //在店接待时长占比
        if(!empty($statisticsData['length'])){
            $length = $statisticsData['length'];
            $lengthRatio['label'] = array();
            $lengthRatio['data'] = array(); 
            foreach ($length as $key => $value) {
                if($key == 180){
                    array_push($lengthRatio['label'],'120分钟以上');
                }else{
                    array_push($lengthRatio['label'],$key.'分钟');
                }
                array_push($lengthRatio['data'],$value);
            }
        }else{
            $lengthRatio['label'] = array("无数据");
            $lengthRatio['data'] = array(0);
        }
        $data['lengthRatio'] = $lengthRatio;

        //联系方式留存数据
        if(!empty($statisticsData['contact'])){
            $contact = $statisticsData['contact'];
            $contactRatio['label'] = array();
            $contactRatio['data'] = array(); 
            foreach ($contact as $key => $value) {
                array_push($contactRatio['label'],$key);
                array_push($contactRatio['data'],$value);
            }
        }else{
            $contactRatio['label'] = array("无数据");
            $contactRatio['data'] = array(0);
        }
        $data['contactRatio'] = $contactRatio;

        //关注车型数据
        if(!empty($statisticsData['vehicle'])){
            $vehicle = $statisticsData['vehicle'];
            $vehicleRatio['label'] = array();
            $vehicleRatio['data'] = array(); 
            foreach ($vehicle as $key => $value) {
                array_push($vehicleRatio['label'],$key);
                array_push($vehicleRatio['data'],$value);
            }
            
        }else{
            $vehicleRatio['label'] = array("无数据");
            $vehicleRatio['data'] = array(0);
        }
        $data['vehicleRatio'] = $vehicleRatio;

        //首次成交比例
        if(!empty($statisticsData['firstToOrder'])){
            $firstToOrder = $statisticsData['firstToOrder'];
            $firstToOrderRatio['label'] = array();
            $firstToOrderRatio['data'] = array(); 
            foreach ($firstToOrder as $key => $value) {
                array_push($firstToOrderRatio['label'],$key);
                array_push($firstToOrderRatio['data'],$value);
            }
            $data['firstToOrderRatio'] = $firstToOrderRatio;
        }

        //再次成交比例
        if(!empty($statisticsData['lastToOrder'])){
            $lastToOrder = $statisticsData['lastToOrder'];
            $lastToOrderRatio['label'] = array();
            $lastToOrderRatio['data'] = array(); 
            foreach ($lastToOrder as $key => $value) {
                array_push($lastToOrderRatio['label'],$key);
                array_push($lastToOrderRatio['data'],$value);
            }
            $data['lastToOrderRatio'] = $lastToOrderRatio;
        }

        //竞品车型数据
        if(!empty($statisticsData['competitor'])){
            $competitor = $statisticsData['competitor'];
            $competitorRatio['label'] = array();
            $competitorRatio['data'] = array(); 
            foreach ($competitor as $key => $value) {
                array_push($competitorRatio['label'],$key);
                array_push($competitorRatio['data'],$value);
            }
            
        }else{
            $competitorRatio['label'] = array("无数据");
            $competitorRatio['data'] = array(0);
        }
        $data['competitorRatio'] = $competitorRatio;

        //本周期日期
        $data['thisStart'] = date('m月d日',$date['thisStart']);
        $data['thisEnd'] = date('m月d日',$date['thisEnd']);
        
        return json($data); 
        // dump($data);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //获取销售顾问数据
        $sales = UserModel::where('visible',1)->column('name');
        View::assign('sales',$sales);

        //获取车系数据
        $vehicle = CarModel::where('valid','1')->Distinct(true)->column('vehicle');
        View::assign('vehicle',$vehicle);

        //获取以往职业数据
        $daterange = date('Y-m-d',strtotime('-30 day'))." - ".date('Y-m-d');
        $date = DateInterval($daterange);
        $occupation = ShowroomModel::whereTime('create_date','between',[$date['thisStart'],$date['thisEnd']])->distinct(true)->column('occupation');
        View::assign('occupation',$occupation);

        //渲染页面
        return view('create');
    }

    /**
     * 客户查重返回json.
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function repeatJson(Request $request)
    {   
        //查询类型
        $type = $request->param('type');

        switch ($type) {
            case 'create':

                //获取客户电话数据
                $phone = $request->param('phone');

                //获取客户配置数据
                $VisitorData = ShowroomModel::where('phone',$phone)->order('id', 'desc')->find();

                if($VisitorData){

                    //如果此前是首次来店的客户就加到再次
                    if($VisitorData['type'] == "首次"){
                        $VisitorData['type'] = "再次";
                    }elseif($VisitorData['type'] == "再次"){
                        $VisitorData['type'] = "三次或以上";
                    }

                    //备注加日期赋值
                    $VisitorData['detail'] = $VisitorData['detail']."(".date("Y年m月d日",strtotime($VisitorData['create_date'])).")\n";
                }

                break;

            case 'edit':

                //获取客户电话数据
                $id = $request->param('id');

                //获取客户配置数据
                $VisitorData = ShowroomModel::find($id);
                
                break;
            
            default:
                # code...
                break;
        }
        

        if($VisitorData){

            //组装关注点
            $foucs = array();
            if($VisitorData['focus_space'] == 1){
                array_push($foucs,'空间');
            }
            if($VisitorData['focus_control'] == 1){
                array_push($foucs,'操控');
            }
            if($VisitorData['focus_power'] == 1){
                array_push($foucs,'动力');
            }
            if($VisitorData['focus_config'] == 1){
                array_push($foucs,'配置');
            }
            if($VisitorData['focus_appearance'] == 1){
                array_push($foucs,'外观');
            }
            $VisitorData['focus'] = $foucs;

            //有就返回json
            return json($VisitorData);
        }else{
            //没有就返回0
            return 0;
        } 
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //获取网页数据
        $data = $request->param();
        //如果竞品为空
        if(empty($data['competitor'])){
            $data['competitor'] = '未填写';
        }
        //分离关注点，分离点为','
        $focus = explode(',',$data['focus']);
        //关注点循环赋值给data
        foreach ($focus as $key => $value) {
            switch ($value) {
                case '空间':
                    $data['focus_space'] = 1;
                    break;
                case '操控':
                    $data['focus_control'] = 1;
                    break;
                case '动力':
                    $data['focus_power'] = 1;
                    break;
                case '配置':
                    $data['focus_config'] = 1;
                    break;
                case '外观':
                    $data['focus_appearance'] = 1;
                    break;
                default:
                    # code...
                    break;
            }
        }
        // 调用create方法写入数据库
        $result = ShowroomModel::create($data);

        //签订订单写入待完善订单列表
        if($data['order'] == 1){
            $orderCount = OrderModel::where('phone',$data['phone'])->count();
            if($orderCount == 0 ){
                $order['create_date'] = $data['create_date'];
                $order['sales'] = $data['sales'];
                $order['name'] = $data['name'];
                $order['phone'] = $data['phone'];
                $order['vehicle'] = $data['vehicle'];
                $order['state'] = 1;
                OrderModel::create($order);//调用create方法写入数据库
            }
        }

        //如果客户类型为交车
        if($data['type'] == '交车'){
            $orderCount = OrderModel::where('phone',$data['phone'])->count();
            if($orderCount != 0){ 
                $order = OrderModel::where('phone',$data['phone'])->order('create_date','desc')->find();
                $order->perfected = 0;
                $order->save();
            }
        }

        if($result == false){
            return 0;
        }else{
            return $result->id;
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //获取此前数据
        $data = ShowroomModel::where('id',$id)->find();

        if($data){

            //组装关注点
            if($data['focus_space'] == 1){
                $focus_space = '空间,';
            }else{
                $focus_space = '';
            }
            if($data['focus_control'] == 1){
                $focus_control = '操控,';
            }else{
                $focus_control = '';
            }
            if($data['focus_power'] == 1){
                $focus_power = '动力,';
            }else{
                $focus_power = '';
            }
            if($data['focus_config'] == 1){
                $focus_config = '配置,';
            }else{
                $focus_config = '';
            }
            if($data['focus_appearance'] == 1){
                $focus_appearance = '外观,';
            }else{
                $focus_appearance = '';
            }
            $data['focus'] = $focus_space . $focus_control . $focus_power . $focus_config . $focus_appearance;
            $data['detail'] = trim($data['detail']);
        }
        
        View::assign('data',$data);

        return view('read'); 
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //获取销售顾问数据
        $sales = UserModel::where('visible',1)->column('name');
        View::assign('sales',$sales);

        //获取车系数据
        $vehicle = CarModel::where('valid','1')->Distinct(true)->column('vehicle');
        View::assign('vehicle',$vehicle);

        //获取此前数据
        $data = ShowroomModel::find($id);
        View::assign('id',$data['id']);

        return view('edit');
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //获取网页数据
        $data = $request->param();
        //分离关注点，分离点为','
        $focus = explode(',',$data['focus']);
        //关注点循环赋值给data
        foreach ($focus as $key => $value) {
            switch ($value) {
                case '空间':
                    $data['focus_space'] = 1;
                    break;
                case '操控':
                    $data['focus_control'] = 1;
                    break;
                case '动力':
                    $data['focus_power'] = 1;
                    break;
                case '配置':
                    $data['focus_config'] = 1;
                    break;
                case '外观':
                    $data['focus_appearance'] = 1;
                    break;
                default:
                    # code...
                    break;
            }
        }
        //调用create方法写入数据库
        $result = ShowroomModel::update($data);

        if($result == false){
            return 0;
        }else{
            return $result->id;
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //删除
        $user = ShowroomModel::find($id);//删除id号
        $result = $user->delete();//确认删除结果，返回布尔值
        if($result){
            return "ok";//成功则返回OK
        }else{
            return "false";//失败则返回false
        }
    }

    private function statistics($startDate,$endDate){

        //性别数据,男1女2
        $sex = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->Distinct(true)->column('sex');

        for ($i=0; $i < count($sex); $i++) { 
            $statisticsData['sex'][$sex[$i]] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where('sex',$sex[$i])->count();
        }

        //客流来源渠道数据
        $sources = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->Distinct(true)->column('sources');

        for ($i=0; $i < count($sources); $i++) { 
            $statisticsData['sources'][$sources[$i]] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where('sources',$sources[$i])->count();
        }

        //信息来源渠道数据
        $origin = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->Distinct(true)->column('origin');

        for ($i=0; $i < count($origin); $i++) { 
            $statisticsData['origin'][$origin[$i]] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where('origin',$origin[$i])->count();
        }

        //停留时长
        $length = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->Distinct(true)->column('length');

        for ($i=0; $i < count($length); $i++) { 
            $statisticsData['length'][$length[$i]] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where('length',$length[$i])->count();
        }

        //首再次来店
        $type = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->Distinct(true)->column('type');

        for ($i=0; $i < count($type); $i++) { 
            $statisticsData['type'][$type[$i]] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where('type',$type[$i])->count();
        }

        //留取联系方式比例
        $contact = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->Distinct(true)->column('contact');

        for ($i=0; $i < count($contact); $i++) { 
            $statisticsData['contact'][$contact[$i]] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where('contact',$contact[$i])->count();
        }

        //车型比例
        $vehicle = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->Distinct(true)->column('vehicle');

        for ($i=0; $i < count($vehicle); $i++) { 
            $statisticsData['vehicle'][$vehicle[$i]] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where('vehicle',$vehicle[$i])->count();
        }

        //首次接待成交率
        $statisticsData['firstToOrder']['订单'] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where(['type' => '首次','order' => 1])->count();
        $statisticsData['firstToOrder']['未订'] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where(['type' => '首次','order' => 0])->count();

        //再次接待成交率
        $statisticsData['lastToOrder']['订单'] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where(['type' => '再次','order' => 1])->count();
        $statisticsData['lastToOrder']['未订'] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where(['type' => '再次','order' => 0])->count();

        //车型比例
        $competitor = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where('competitor','NOTNULL')->Distinct(true)->column('competitor');

        for ($i=0; $i < count($competitor); $i++) { 
            $statisticsData['competitor'][$competitor[$i]] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where('competitor',$competitor[$i])->count();
        }

        return $statisticsData;
    }

}
